package com.jumi.microservice.rocketmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.order.ConsumeOrderContext;
import com.aliyun.openservices.ons.api.order.MessageOrderListener;
import com.aliyun.openservices.ons.api.order.OrderAction;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.dto.invoice.InvoiceOneRequest;
import com.jumi.microservice.dto.invoice.InvoiceOrderRequest;
import com.jumi.microservice.entity.UserOrder;
import com.jumi.microservice.enumerate.OrderStatusEnum;
import com.jumi.microservice.utils.NuoNuoUtil;
import com.jumi.microservice.utils.nuonuo.QueryThirdCommonRequest;
import com.jumi.microservice.entity.JumiInvoice;
import com.jumi.microservice.entity.OrderGoods;
import com.jumi.microservice.enumerate.InvoiceStatusEnum;
import com.jumi.microservice.mapper.InvoiceListMapper;
import com.jumi.microservice.mapper.InvoiceMapper;
import com.jumi.microservice.mapper.OrderGoodsMapper;
import com.jumi.microservice.mapper.UserOrderMapper;
import com.jumi.microservice.service.IWalletInvoiceService;
import com.jumi.microservice.service.invoice.InvoiceApiService;
import com.jumi.microservice.service.invoice.admin.InvoiceService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class InvoiceMessageListener implements MessageListener {
    private static final Logger log = LoggerFactory.getLogger(InvoiceMessageListener.class);
    @Resource
    InvoiceService invoiceService;
    @Resource
    OrderGoodsMapper orderGoodsMapper;
    @Resource
    UserOrderMapper userOrderMapper;
    @Resource
    InvoiceMapper invoiceMapper;
    @Resource
    InvoiceListMapper invoiceListMapper;
    @Resource
    InvoiceApiService invoiceApiService;
    @DubboReference
    private IWalletInvoiceService walletInvoiceService;
    @Resource
    NuoNuoUtil nuoNuoUtil;


    @Override
    public Action consume(Message message, ConsumeContext context) {
        String messageStr = new String(message.getBody()).replace("\"", "");
        log.info("消息队列的数据是[{}]", messageStr);
        JSONObject jsonObject = JSONObject.parseObject(messageStr);
        String orderNo = jsonObject.getString("orderNo");
        Integer goodsId = jsonObject.getInteger("goodsId");
        Integer complete = jsonObject.getInteger("complete");
        log.info("订单编号是[{}]", orderNo);
        log.info("商品id是[{}]", goodsId);
        log.info("是否是全退  1全退  0部分[{}]", complete);
        QueryWrapper<UserOrder> userOrderQueryWrapper = new QueryWrapper<>();
        userOrderQueryWrapper.lambda().eq(UserOrder::getOrderNo, orderNo);
        UserOrder userOrder = userOrderMapper.selectOne(userOrderQueryWrapper);
        log.info("查询出来的数据是[{}]", JSON.toJSONString(userOrder));
        QueryWrapper<OrderGoods> orderAfter = new QueryWrapper<>();
        orderAfter.lambda().eq(OrderGoods::getOrderNo, orderNo);
        // 判断订单下的商品是否全退
        List<OrderGoods> orderGoodsAfter = orderGoodsMapper.selectList(orderAfter);
        boolean afterStatus = false;
        for (OrderGoods orderGood : orderGoodsAfter) {
            if (!orderGood.getGoodsAmount().equals(orderGood.getReturnCount())) {
                afterStatus = true;
            }
        }
        log.info("判断是否全退商品数据是[{}]", JSON.toJSONString(orderGoodsAfter));
        log.info("状态是[{}]", afterStatus);
        if (userOrder.getOrderStatus().equals(OrderStatusEnum.COMPLETED.getCode())) {
            log.info("确认收货逻辑");
            if (complete == 0 && afterStatus) {
                log.info("进入重新开票的接口");
                QueryThirdCommonRequest request = new QueryThirdCommonRequest();
                request.setOrderno(orderNo);
                invoiceApiService.invoiceToAllVoid(request);
                log.info("作废成功,重新开票");
                InvoiceOneRequest invoiceOneRequest = new InvoiceOneRequest();
                invoiceOneRequest.setOrderNum(request.getOrderno());
                //拼接发票id 专用接口
                invoiceApiService.returnInvoice(invoiceOneRequest);
            } else {
                log.info("进入发票作废接口");
                InvoiceOrderRequest invoiceOrderRequest = new InvoiceOrderRequest();
                invoiceOrderRequest.setGoodsId(goodsId);
                invoiceOrderRequest.setOrderNo(orderNo);
                invoiceApiService.invoiceToVoid(invoiceOrderRequest);
            }

        } else {
            log.info("未确认收货逻辑");
            QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
            orderGoodsQueryWrapper.lambda().eq(OrderGoods::getOrderNo, orderNo);
            List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
            log.info("商品数据是[{}]", JSON.toJSONString(orderGoodsList));
            boolean response = true;
            for (OrderGoods orderGoods : orderGoodsList) {
                if (!orderGoods.getReturnCount().equals(orderGoods.getGoodsAmount())) {
                    response = false;
                }
            }
            if (!response) {
                log.info("进入更新发票的接口");
                QueryWrapper<JumiInvoice> invoiceQueryWrapper = new QueryWrapper<>();
                invoiceQueryWrapper.lambda().eq(JumiInvoice::getOrderNum, orderNo).eq(JumiInvoice::getIsRevoke, 0);
                JumiInvoice jumiInvoice = invoiceMapper.selectOne(invoiceQueryWrapper);
                jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.STA_WAIT_BILLED.getCode().byteValue());
                BigDecimal price = new BigDecimal(0);
                BigDecimal returnPrice = new BigDecimal(0);
//                //金额
                for (OrderGoods orderGoods : orderGoodsList) {
                    //退款总额
                    returnPrice = returnPrice.add(orderGoods.getReturnPrice());
                    //商品总额
                    price = price.add(orderGoods.getGoodsPrice().multiply(new BigDecimal(orderGoods.getGoodsAmount())));
                }
                BigDecimal totalPrice = price.subtract(returnPrice);
                jumiInvoice.setInvoiceAmount(totalPrice);
                int row = invoiceMapper.updateById(jumiInvoice);
                log.info("更新发票是否成功 0/1[{}]", row);
            } else {
                log.info("进入删除发票的接口");
                QueryWrapper<JumiInvoice> invoiceQueryWrapper = new QueryWrapper<>();
                invoiceQueryWrapper.lambda().eq(JumiInvoice::getOrderNum, orderNo).eq(JumiInvoice::getIsRevoke, 0);
                JumiInvoice jumiInvoice = invoiceMapper.selectOne(invoiceQueryWrapper);
                jumiInvoice.setIsRevoke((byte) 1);
                jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.NO_INVOICE.getCode().byteValue());
                int row = invoiceMapper.updateById(jumiInvoice);
                log.info("更新发票是否成功 0/1[{}]", row);
            }
        }
        return Action.CommitMessage;
    }
}

